#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time: 2023/6/14 11:01
# @Author: Anthony (anthony66888@163.com)
# @description: 
"""
import ast
import datetime
import os
import random
from typing import Text

import yaml


def root_path():
    """ 获取 根路径 """
    path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # path = os.path.dirname(os.path.abspath(''))
    return path


def ensure_path_sep(path: Text) -> Text:
    """兼容 windows 和 linux 不同环境的操作系统路径 """
    if "/" in path:
        path = os.sep.join(path.split("/"))

    if "\\" in path:
        path = os.sep.join(path.split("\\"))

    return root_path() + path


class YamlControl:
    """ 获取 yaml 文件中的数据 """

    def __init__(self, file_dir):
        self.file_dir = ensure_path_sep(str(file_dir))

    def read_yaml(self) -> dict:
        """
        获取 yaml 中的数据
        :param: fileDir:
        :return:
        """
        # 判断文件是否存在
        # file_path = ensure_path_sep(self.file_dir)
        if os.path.exists(self.file_dir):
            data = open(self.file_dir, 'r', encoding='utf-8')
            res = yaml.load(data, Loader=yaml.FullLoader)
            data.close()
        else:
            raise FileNotFoundError("文件路径不存在")
        return res

    def write_yaml(self, data):
        with open(self.file_dir, 'w') as f:
            yaml.dump(data, f, default_flow_style=False)

        f.close()

    def update_key_yaml(self, father_key, father_value=None,
                        child_key=None, child_value=None,
                        condition_key=None, condition_value=None):
        """

        @param father_key: 父键key
        @param father_value: 父键值
        @param child_key: 子键key
        @param child_value: 子键值
        @param condition_key: 条件子键key
        @param condition_value: 条件子键值
        """
        with open(self.file_dir, 'r') as f:
            data = yaml.safe_load(f)

        if data is None:
            data = {father_key: father_value}

        elif father_key in data:
            if child_key is None:
                data[father_key] = father_value  # 存在则更新
            else:
                # 修改指定子键的值
                [d.update({child_key: child_value}) for d in data[father_key] if d[condition_key] == condition_value]
                # for d in data[father_key]:
                #     if d[condition_key] == condition_value:
                #         d[child_key] = child_value
        else:
            data.update({father_key: father_value})  # 不存在则新增

        # 写入更新后的 YAML 文件
        with open(self.file_dir, 'w') as file:
            yaml.dump(data, file, default_flow_style=False)

        f.close()

    def del_user_yaml(self, key, condition, del_value):
        # 读取YAML文件中的数据
        with open(self.file_dir, 'r') as f:
            data = yaml.safe_load(f)

        # 删除token为123的字典
        data[key] = [d for d in data[key] if d[condition] != del_value]
        # 将更改后的数据写入YAML文件
        self.write_yaml(data)
        f.close()

    def del_dict_list(self, key, value):
        with open(self.file_dir, 'r') as f:
            data = yaml.safe_load(f)

        # 删除token为123的字典
        # data[key] = [d for d in data[key] if d[condition] != del_value]
        data[key] = data[key].remove[value]

        # 将更改后的数据写入YAML文件
        self.write_yaml(data)
        f.close()


if __name__ == '__main__':
    player_config = YamlControl("/data/dream_user_info.yaml")
    f_key = 'user_info1'
    cd_key = 'uid'
    cd_value = '281'
    c_key = 'token'
    c_value = 'test2133'

    player_config.update_key_yaml(father_key=f_key, child_key=c_key, child_value=c_value,
                                  condition_key=cd_key, condition_value=cd_value)
    value = player_config.read_yaml()
    print(value)


